<template>
  <div id="VodResourcePage">
    <div class="search-wrapper">
      <div class="title-wrapper">
        <span class="title">点播筛选</span>
      </div>
      <div class="content-wrapper">
        <div class="search-item">
          <span class="item-label">区域</span>
          <el-select
            class="item-input"
            v-model="queryObj.areaName"
            placeholder="选择区域"
            clearable
            filterable
            @change="areaChangeHandle"
          >
            <el-option
              v-for="item in globalData.areaList"
              :key="item"
              :label="item"
              :value="item"
            />
          </el-select>
        </div>
        <div class="search-item">
          <span class="item-label">栏目名</span>
          <el-select
            class="item-input"
            v-model="queryObj.programName"
            placeholder="选择栏目"
            clearable
            filterable
            @change="programNameChangeHandle"
          >
            <el-option
              v-for="item in globalData.programList"
              :key="item"
              :label="item"
              :value="item"
            />
          </el-select>
        </div>
        <div class="search-item">
          <span class="item-label">时间段</span>
          <el-date-picker
            v-model="timeRange"
            type="datetimerange"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            format="YYYY-MM-DD HH:mm:ss"
            date-format="YYYY/MM/DD ddd"
            time-format="HH:mm:ss"
            :disabled-date="disabledDate"
            :disabled-time="disabledTime"
            @change="timeRangeChangeHandle"
            @clear="timeRangeChangeHandle"
          />
        </div>
        <div class="search-item">
          <span class="item-label">下载状态</span>
          <el-select
            class="item-input download-status-select"
            v-model="queryObj.downloadStatus"
            placeholder="选择下载状态"
            clearable
            @change="downloadStatusChangeHandle"
          >
            <el-option
              v-for="item in downloadStatusList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </div>
        <div class="search-btn" @click="searchHandle">筛选</div>
        <div v-if="isShowAddBtn" class="add-btn" @click="addHandle">添加</div>
      </div>
    </div>
    <div class="data-wrapper">
      <div class="title-wrapper">
        <span class="title">资源详情</span>
      </div>
      <div class="table-wrapper">
        <el-table
          :data="tableData"
          stripe
          fit
          class="self-stripe-table"
          height="100%"
        >
          <el-table-column type="index" label="序号" width="100" />
          <el-table-column prop="areaName" label="区域" width="150" />
          <el-table-column prop="programName" label="栏目" width="200" />
          <el-table-column label="时间段" min-width="200">
            <template #default="scope">
              <div class="time-range">
                <div class="time-period">
                  {{ formatTime(scope.row.startTime) }} -
                  {{ formatTime(scope.row.endTime) }}
                </div>
                <div v-if="false" class="duration">
                  时长：{{
                    formatDuration(scope.row.startTime, scope.row.endTime)
                  }}
                </div>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="点播地址" min-width="200">
            <template #default="scope">
              <div>{{ scope.row.previewUrl }}</div>
            </template>
          </el-table-column>
          <el-table-column label="下载状态" width="150">
            <template #default="scope">
              <div
                class="download-status"
                :class="{
                  'not-download':
                    scope.row.downloadStatus === 0 &&
                    !downloadingIds.has(scope.row.id),
                  downloading: downloadingIds.has(scope.row.id),
                  downloaded:
                    scope.row.downloadStatus === 1 &&
                    !downloadingIds.has(scope.row.id),
                }"
              >
                {{
                  downloadingIds.has(scope.row.id)
                    ? "下载中..."
                    : scope.row.downloadStatus === 0
                    ? "未下载"
                    : "已下载"
                }}
              </div>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="150">
            <template #default="scope">
              <div
                v-if="scope.row.downloadStatus === 0"
                class="table-btn"
                :class="{ disabled: downloadingIds.has(scope.row.id) }"
                @click="downloadHandle(scope.row)"
              >
                下载
              </div>
              <div
                v-if="
                  scope.row.downloadStatus === 1 &&
                  !downloadingIds.has(scope.row.id)
                "
                class="table-btn"
                @click="previewHandle(scope.row.previewUrl)"
              >
                查看
              </div>
              <div
                v-if="isShowAddBtn"
                class="table-btn"
                @click="editHandle(scope.row)"
              >
                编辑
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>

    <!-- 分页 -->
    <div v-if="pagination.totalPages > 1" class="pagination-wrapper">
      <el-pagination
        v-model="pagination.currentPage"
        :total="pagination.totalCount"
        :page-size="pagination.numPerPage"
        background
        :hide-on-single-page="true"
        @size-change="sizeChangeHandle"
        @current-change="currentChangeHandle"
      />
    </div>
    <!-- 预览弹框 -->
    <el-dialog
      class="self-dialog"
      v-model="previewDialogVisible"
      title="栏目详情"
      width="70%"
    >
      <div class="preview-wrapper">
        <div class="preview-player">
          <XGPlayer :url="previewUrl" />
          <!-- <ckplayer
            :data="{
              url: previewUrl,
              name: '点播预览',
              isLive: true,
              flashplayer: false,
              autoplay: true,
              videoUrl: previewUrl,
            }"
          ></ckplayer> -->
        </div>
      </div>
    </el-dialog>

    <!-- 添加资源弹框 -->
    <el-dialog
      class="self-dialog"
      v-model="addDialogVisible"
      title="添加点播资源"
      width="50%"
      @close="resetAddForm"
      @opened="handleDialogOpened"
    >
      <el-form
        ref="addFormRef"
        :model="addForm"
        :rules="addFormRules"
        label-width="100px"
        label-position="right"
      >
        <el-form-item label="区域" prop="areaName">
          <el-select
            v-model="addForm.areaName"
            filterable
            placeholder="选择区域"
            style="width: 100%"
          >
            <el-option
              v-for="item in globalData.areaList"
              :key="item"
              :label="item"
              :value="item"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="栏目名" prop="programName">
          <el-select
            v-model="addForm.programName"
            filterable
            placeholder="选择栏目"
            style="width: 100%"
          >
            <el-option
              v-for="item in globalData.programList"
              :key="item"
              :label="item"
              :value="item"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="时间段" prop="timeRange">
          <el-date-picker
            :key="datePickerKey"
            v-model="addForm.timeRange"
            type="datetimerange"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            format="YYYY-MM-DD HH:mm:ss"
            date-format="YYYY/MM/DD"
            time-format="HH:mm:ss"
            :default-time="[
              new Date(2000, 1, 1, 12, 0, 0),
              new Date(2000, 1, 1, 12, 0, 0),
            ]"
            style="width: 100%"
            :disabled-date="disabledDate"
            :disabled-time="disabledTime"
            :editable="false"
          />
        </el-form-item>

        <el-form-item label="下载状态" prop="downloadStatus">
          <el-select
            v-model="addForm.downloadStatus"
            placeholder="选择下载状态"
            style="width: 100%"
          >
            <el-option label="未下载" :value="0" />
            <el-option label="已下载" :value="1" />
          </el-select>
        </el-form-item>

        <el-form-item label="点播地址" prop="previewUrl">
          <el-input
            v-model="addForm.previewUrl"
            placeholder="输入点播地址"
            type="textarea"
            :rows="3"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="addDialogVisible = false">取消</el-button>
          <el-button
            type="primary"
            @click="submitAddForm"
            :loading="addFormLoading"
          >
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, getCurrentInstance, watch, nextTick } from "vue";
import { ElMessage } from "element-plus";
import { ListResponseType, PaginationType } from "@/api/globalType";
import {
  getVodResourceListAPI,
  addOrUpdateVodResourceAPI,
  downloadVodResourceAPI,
  GetVodResourceListQueryType,
  VodResourceType,
  AddOrUpdateVodResourceQueryType,
  DownloadVodResourceResponseType,
} from "@/api/service/vodResource";
import XGPlayer from "@/components/Player/xgplayer.vue";
import ckplayer from "@/components/Player/ckplayer.vue";
import { formatTime, formatDuration } from "@/assets/js/utils";
import { useRoute } from "vue-router";

const route = useRoute();
const addBtn = route.query.addBtn as string;
const isShowAddBtn = ref(true);
if (addBtn === "true") {
  isShowAddBtn.value = true;
}

const instance = getCurrentInstance();
// 访问全局数据
const globalData = instance?.appContext.config.globalProperties.$globalData;

// 下载状态
const downloadStatusList = ref([
  {
    label: "未下载",
    value: 0,
  },
  {
    label: "已下载",
    value: 1,
  },
]);
// 查询条件
const queryObj = ref<GetVodResourceListQueryType>({
  areaName: "",
  programName: "",
  downloadStatus: null,
  startTime: "",
  endTime: "",
});
// 时间段
const timeRange = ref<string[]>([]);
// 分页
const pagination = ref<PaginationType>({
  currentPage: 1,
  numPerPage: 50,
  totalCount: 0,
  totalPages: 0,
});

// 表格数据
const tableData = ref<VodResourceType[]>([]);

// API调用保护状态
const listApiLoading = ref(false);

function getVodResourceList() {
  // 防止并发调用
  if (listApiLoading.value) return;

  listApiLoading.value = true;

  getVodResourceListAPI({
    areaName: queryObj.value.areaName,
    programName: queryObj.value.programName,
    downloadStatus: queryObj.value.downloadStatus,
    startTime: queryObj.value.startTime,
    endTime: queryObj.value.endTime,
    currentPage: pagination.value.currentPage,
    numPerPage: pagination.value.numPerPage,
  })
    .then((_data: any) => {
      const data = _data as ListResponseType<VodResourceType>;
      tableData.value = data.list;
      pagination.value.currentPage = data.currentPage;
      pagination.value.numPerPage = data.numPerPage;
      pagination.value.totalCount = data.totalCount;
      pagination.value.totalPages = data.totalPages;
    })
    .catch(() => {
      ElMessage.error("获取点播资源列表失败");
    })
    .finally(() => {
      listApiLoading.value = false;
    });
}
getVodResourceList();

// 区域变化
function areaChangeHandle(areaName: string) {
  pagination.value.currentPage = 1;
  queryObj.value.areaName = areaName;
  getVodResourceList();
}

// 栏目名变化
function programNameChangeHandle(programName: string) {
  pagination.value.currentPage = 1;
  queryObj.value.programName = programName;
  getVodResourceList();
}

// 下载状态变化
function downloadStatusChangeHandle(downloadStatus: number | null) {
  pagination.value.currentPage = 1;
  queryObj.value.downloadStatus = downloadStatus;
  getVodResourceList();
}

// 时间段变化
function timeRangeChangeHandle(dates: string[]) {
  pagination.value.currentPage = 1;
  if (dates && dates.length) {
    timeRange.value = dates;
    queryObj.value.startTime = formatTime(dates[0]);
    queryObj.value.endTime = formatTime(dates[1]);
  } else {
    queryObj.value.startTime = "";
    queryObj.value.endTime = "";
  }
  getVodResourceList();
}

// 禁用当前时间之后的日期
function disabledDate(time: Date) {
  const today = new Date();
  // 重置今天的时间为00:00:00进行比较
  today.setHours(0, 0, 0, 0);
  const targetDate = new Date(time);
  targetDate.setHours(0, 0, 0, 0);

  return targetDate.getTime() > today.getTime();
}

// 禁用当前时间之后的时间
function disabledTime(time: Date, type: "start" | "end") {
  const now = new Date();
  const selectedDate = new Date(time);

  // 如果选择的不是今天，则不禁用任何时间
  if (selectedDate.toDateString() !== now.toDateString()) {
    return {};
  }

  // 如果是今天，则禁用当前时间之后的时间
  const currentHour = now.getHours();
  const currentMinute = now.getMinutes();
  const currentSecond = now.getSeconds();

  return {
    disabledHours: () => {
      const hours = [];
      for (let i = currentHour + 1; i < 24; i++) {
        hours.push(i);
      }
      return hours;
    },
    disabledMinutes: (hour: number) => {
      if (hour === currentHour) {
        const minutes = [];
        for (let i = currentMinute + 1; i < 60; i++) {
          minutes.push(i);
        }
        return minutes;
      }
      return [];
    },
    disabledSeconds: (hour: number, minute: number) => {
      if (hour === currentHour && minute === currentMinute) {
        const seconds = [];
        for (let i = currentSecond + 1; i < 60; i++) {
          seconds.push(i);
        }
        return seconds;
      }
      return [];
    },
  };
}

// 筛选
function searchHandle() {
  pagination.value.currentPage = 1;
  getVodResourceList();
}

// 分页大小变化
function sizeChangeHandle(size: number) {
  pagination.value.numPerPage = size;
  pagination.value.currentPage = 1;
  getVodResourceList();
}

// 分页当前页变化
function currentChangeHandle(currentPage: number) {
  pagination.value.currentPage = currentPage;
  getVodResourceList();
}

// 下载视频、预览视频相关状态
const previewDialogVisible = ref(false);
const currentVideoUrl = ref<string>(""); // 当前要预览的原始视频URL
const localVideoUrl = ref<string>(""); // 获取到的预览URL
const isDownloadingVideo = ref(false);
const downloadError = ref(false);
const previewUrl = ref<string>("");

// 下载状态控制 - 记录正在下载的资源ID
const downloadingIds = ref(new Set<string>());

function downloadHandle(row: VodResourceType) {
  // 检查是否已在下载中，防止重复调用
  if (downloadingIds.value.has(row.id)) {
    return;
  }

  if (!row.previewUrl) {
    ElMessage.error("点播地址为空");
    return;
  }

  // 添加到下载中列表
  downloadingIds.value.add(row.id);

  downloadVodResourceAPI({
    vodResourceId: row.id,
    videoUrl: row.previewUrl,
  })
    .then((_data: any) => {
      const data = _data as DownloadVodResourceResponseType;
      console.log(data);

      // 更新本地数据状态为已下载
      const targetRow = tableData.value.find((item) => item.id === row.id);
      if (targetRow) {
        targetRow.downloadStatus = 1;
      }

      previewUrl.value = data.previewUrl;
      previewDialogVisible.value = true;
      ElMessage.success("下载成功");
    })
    .catch(() => {
      ElMessage.error("下载视频失败");
    })
    .finally(() => {
      // 从下载中列表移除
      downloadingIds.value.delete(row.id);
    });
}

// 预览视频 - 调用下载接口获取预览地址
async function previewHandle(url: string) {
  if (!url) {
    url = globalData.defaultProgramPreviewUrl;
  }
  previewUrl.value = url;
  previewDialogVisible.value = true;
}

// 监听对话框关闭，清理状态
function handleDialogClose() {
  previewUrl.value = "";
}

// 监听对话框可见性变化
watch(previewDialogVisible, (newValue) => {
  if (!newValue) {
    handleDialogClose();
  }
});

// 添加资源
const addDialogVisible = ref(false);
const addFormRef = ref();
const addFormLoading = ref(false);
// 日期选择器的key，用于强制重新渲染
const datePickerKey = ref(0);

function addHandle() {
  // 强制重新渲染日期选择器，确保是全新的组件实例
  datePickerKey.value += 1;
  addDialogVisible.value = true;
}

// 弹框打开后的处理
function handleDialogOpened() {
  // 等待DOM更新后清除验证状态
  nextTick(() => {
    addFormRef.value?.clearValidate();
  });
}

// 编辑资源
function editHandle(row: VodResourceType) {
  // 强制重新渲染日期选择器，确保是全新的组件实例
  datePickerKey.value += 1;

  // 先设置所有数据，包括时间范围
  addForm.value = {
    id: row.id,
    areaName: row.areaName,
    programName: row.programName,
    downloadStatus: row.downloadStatus,
    signalStatus: row.signalStatus || 0,
    previewUrl: row.previewUrl,
    timeRange: row.startTime && row.endTime ? [row.startTime, row.endTime] : [], // 直接设置时间范围
  };

  // 然后打开弹框 - handleDialogOpened会自动处理后续逻辑
  addDialogVisible.value = true;
}

// 添加表单数据
const addForm = ref<AddOrUpdateVodResourceQueryType & { timeRange: string[] }>({
  id: "",
  areaName: "",
  programName: "",
  downloadStatus: 0,
  signalStatus: 0,
  previewUrl: "",
  timeRange: [],
});

// 表单验证规则 - 设置为手动触发，避免弹框打开时就显示错误
const addFormRules = {
  areaName: [{ required: true, message: "选择区域", trigger: "blur" }],
  programName: [{ required: true, message: "选择栏目", trigger: "blur" }],
  timeRange: [{ required: true, message: "选择时间段", trigger: "blur" }],
  downloadStatus: [
    { required: true, message: "选择下载状态", trigger: "blur" },
  ],
};

// 重置添加表单
function resetAddForm() {
  addForm.value = {
    id: "",
    areaName: "",
    programName: "",
    downloadStatus: 0,
    signalStatus: 0,
    previewUrl: "",
    timeRange: [],
  };
  addFormRef.value?.clearValidate();
  addFormRef.value?.resetFields();

  // 强制重新渲染日期选择器，清除其内部状态
  datePickerKey.value += 1;
}

// 提交添加表单
function submitAddForm() {
  // 防止并发提交
  if (addFormLoading.value) return;

  addFormRef.value?.validate((valid: boolean) => {
    if (valid) {
      addFormLoading.value = true;

      // 处理时间段
      let startTime = "";
      let endTime = "";
      if (addForm.value.timeRange && addForm.value.timeRange.length === 2) {
        startTime = formatTime(addForm.value.timeRange[0]);
        endTime = formatTime(addForm.value.timeRange[1]);
      }

      addOrUpdateVodResourceAPI({
        id: addForm.value.id,
        areaName: addForm.value.areaName,
        programName: addForm.value.programName,
        downloadStatus: addForm.value.downloadStatus,
        signalStatus: addForm.value.signalStatus,
        previewUrl: addForm.value.previewUrl,
        startTime,
        endTime,
      })
        .then(() => {
          ElMessage.success(
            addForm.value.id ? "编辑点播资源成功" : "添加点播资源成功"
          );
          addDialogVisible.value = false;
          resetAddForm();
          // 刷新列表
          pagination.value.currentPage = 1;
          getVodResourceList();
        })
        .catch(() => {
          ElMessage.error(
            addForm.value.id ? "编辑点播资源失败" : "添加点播资源失败"
          );
        })
        .finally(() => {
          addFormLoading.value = false;
        });
    }
  });
}
</script>

<style scoped lang="scss">
#VodResourcePage {
  height: 100%;
  display: flex;
  flex-direction: column;
}
.title-wrapper {
  position: relative;
  display: flex;
  align-items: center;
  min-height: 2rem;
  padding-left: 2rem;
  color: $color_brand;
  font-size: $font-size-block-title;
}
.title-wrapper::before {
  position: absolute;
  left: 0;
  top: 50%;
  display: block;
  content: "";
  width: 3px;
  height: 1.8rem;
  background-color: $color_brand;
  transform: translateY(-50%);
}
.search-wrapper {
  background-color: #fff;
  flex-shrink: 0;
  padding: 1.5rem 0;
  border-bottom: 1px solid $border-color-primary;
  .content-wrapper {
    position: relative;
    display: flex;
    flex-wrap: wrap;
    padding: 2rem 2rem 0 2rem;
  }
  .search-item {
    display: flex;
    align-items: center;
    flex-shrink: 0;
    margin-bottom: 1rem;
    margin-right: 2rem;
    .item-label {
      display: inline-block;
      padding-right: 1rem;
      white-space: nowrap;
      text-align: right;
      color: $text-color-regular;
      font-size: $font-size-base;
    }
    .item-input {
      width: 20rem;
    }
    .download-status-select {
      width: 15rem;
    }
  }
  .search-item:last-child {
    margin-right: 0;
  }
  .search-btn {
    display: flex;
    align-items: center;
    flex-shrink: 0;
    height: 3rem;
    padding: 0 1.5rem;
    margin-bottom: 1rem;
    background-color: $color_brand;
    color: #fff;
    border-radius: 0.5rem;
    cursor: pointer;
    white-space: nowrap;
  }
  .add-btn {
    position: absolute;
    right: 5.8rem;
    top: 2rem;
    display: flex;
    align-items: center;
    height: 3rem;
    padding: 0 1.5rem;
    background-color: $color_brand;
    color: #fff;
    border-radius: 0.5rem;
    cursor: pointer;
  }
}
.data-wrapper {
  flex: 1;
  min-height: 0;
  padding: 1.5rem 0;
  background-color: #fff;
  display: flex;
  flex-direction: column;
  .table-wrapper {
    flex: 1;
    min-height: 0;
    padding: 0 2rem;
    margin-top: 1.5rem;
  }
  .table-btn {
    display: inline-flex;
    align-items: center;
    background-color: $color_brand;
    color: #fff;
    margin-left: 0.5rem;
    padding: 0 1rem;
    border-radius: 0.5rem;
    font-size: $font-size-base-btn-text;
    cursor: pointer;
  }
  .table-btn:first-child {
    margin-left: 0;
  }
  .table-btn:hover {
    text-decoration: underline;
  }
  .download-status.downloaded {
    color: $color_success;
  }
  .download-status.downloading {
    color: $color_brand;
  }
  .table-btn.disabled {
    background-color: #a0a0a0;
    cursor: not-allowed;
    pointer-events: none;
  }
  .time-range {
    .time-period {
      color: $text-color-regular;
    }
    .duration {
      font-size: 1.2rem;
      color: $text-color-secondary;
    }
  }
}

// 分页区域样式
.pagination-wrapper {
  flex-shrink: 0;
}

.preview-wrapper {
  width: 100%;
  padding-top: 56.25%;
  position: relative;
  .preview-player {
    width: 100%;
    height: 100%;
    position: absolute;
    top: 0;
    left: 0;
  }
}

// 添加资源弹框样式
:deep(.el-form-item__label) {
  color: $text-color-regular;
  font-weight: normal;
}

:deep(.el-input__wrapper) {
  border-radius: 0.5rem;
}

:deep(.el-select .el-input__wrapper) {
  border-radius: 0.5rem;
}

:deep(.el-button--primary) {
  background-color: $color_brand;
  border-color: $color_brand;
  border-radius: 0.5rem;
}

:deep(.el-button) {
  border-radius: 0.5rem;
}

.dialog-footer {
  text-align: right;
}

// 旋转动画
@keyframes rotate {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}
</style>
